package BinaryTree;

import com.sun.source.tree.Tree;

public class binaryTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int val){
            this.val=val;
        }
    }
    public TreeNode root=null;
    public TreeNode search(int key){
        TreeNode cur=root;
        while(cur!=null){
            if(cur.val<key){
                cur=cur.right;
            }else if(cur.val>key){
                cur=cur.left;
            }else{
                return cur;
            }
        }
        return null;
    }
    //所有的插入一定是插入到了叶子节点
    public void insert(int val){
        TreeNode node =new TreeNode(val);
        TreeNode cur=root;
        TreeNode parent=null;
        if(root==null){
            root=node;
            return;
        }
        while(cur!=null){
            parent=cur;
            if(cur.val>val){
                cur=cur.left;
            }else if(cur.val>val){
                cur=cur.right;
            }else{
                return;
            }
            if(parent.val>val){
                parent.left=node;
            }else{
                parent.right=node;
            }
        }
    }

    public  void remove(int key){
        TreeNode parent=null;
        TreeNode cur=root;
        while(cur!=null){
            if(cur.val<key){
                parent=cur;
                cur=cur.right;
            }else if(cur.val>key){
                parent=cur;
                cur=cur.left;
            }else{
                removeNode(parent,cur);
                return;
            }
        }
    }
    public void removeNode(TreeNode parent,TreeNode cur){
        if(cur.left==null){
            if(cur==root){
                root=cur.right;
            }else if(cur==parent.left){
                parent.left=cur.right;
            }else{
                parent.right=cur.right;
            }

        }else if(cur.right==null){
            if(cur==null){
                root=cur.left;
            }else if(cur==parent.left){
                parent.left=cur.left;
            }else{
                parent.right=cur.left;
            }
        }else{
            TreeNode target=cur.right;
            TreeNode targetP=cur;
            while(target.left!=null){
                targetP=target;
                target=target.left;
            }
            cur.val=target.val;
            if(target==targetP.left){
                targetP.left=target.right;
            }else{
                targetP.right=target.right;
            }

        }
    }

}
